﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using Excel = Microsoft.Office.Interop.Excel;
using Office = Microsoft.Office.Core;
using Microsoft.Office.Tools.Excel;
using Microsoft.Office.Tools.Excel.Extensions;
using System.Windows.Forms;
using System.IO;
using EncryptionLib.Users;

namespace ExcelDiSign
{
    public partial class ThisAddIn
    {
        #region Private members

        private Excel.Application myApplication;

        #endregion

        protected override Microsoft.Office.Core.IRibbonExtensibility
            CreateRibbonExtensibilityObject()
        {
            Ribbon ribbon = new Ribbon();
            ribbon.RibbonCommandClicked += new RibbonCommandHandler(ribbon_RibbonCommandClicked);
            return ribbon;
        }

        private void ThisAddIn_Startup(object sender, System.EventArgs e)
        {
            System.Windows.Forms.Application.EnableVisualStyles();
            myApplication = this.Application;
        }

        private void ThisAddIn_Shutdown(object sender, System.EventArgs e)
        {
        }

        void ribbon_RibbonCommandClicked(Ribbon ribbon, RibbonCommands cmd)
        {
            switch (cmd)
            {
                case RibbonCommands.Help:
                    StringBuilder str = new StringBuilder();
                    str.Append("=== EncryptionLib Add-in for Excel 2007 ===\r\n\r\n");
                    str.Append(" - Sign: choose a place to save the signature file.\r\n");
                    str.Append(" - Verify: choose the appropriate signature file to verify.\r\n\r\n");
                    str.Append(" Sorry for this stupid manual, but I'm pretty lazy now...");
                    MessageBox.Show(null, str.ToString(), "Lazy Manual",
                        MessageBoxButtons.OK, MessageBoxIcon.Information);
                    break;
                case RibbonCommands.Sign:
                    DoSign();
                    break;
                case RibbonCommands.Verify:
                    DoVerify();
                    break;
            }
        }

        #region private utilities

        private string SaveWorkbook()
        {
            Excel.Workbook doc = myApplication.ActiveWorkbook;
            string sFilePath = doc.FullName;
            FileInfo fInfo;
            try
            {
                fInfo = new FileInfo(sFilePath);
            }
            catch (System.Exception ex)
            {
                MessageBox.Show(null,
                    string.Format("Cannot access to the workbook.\r\nError: {0}", ex.Message),
                    "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return string.Empty;
            }

            if (!doc.Saved || !fInfo.Exists)
            {
                if (MessageBox.Show(null,
                    "You have to save the workbook before sign it.\r\nDo you want to save the workbook now?",
                    "Save", MessageBoxButtons.YesNo, MessageBoxIcon.Question)
                    == DialogResult.No)
                    return string.Empty;
                else
                    doc.Save();
            }
            doc = myApplication.ActiveWorkbook;
            sFilePath = doc.FullName;
            return sFilePath;
        }

        private void DoSign()
        {
            string sFilePath = SaveWorkbook();

            if (!string.IsNullOrEmpty(sFilePath))
            {
                frmSign f = new frmSign();
                f.DocumentPath = sFilePath;
                f.UserManager = LoadUserDatabase();
                f.ShowDialog(null);
            }
        }

        private void DoVerify()
        {
            string sFilePath = SaveWorkbook();

            if (!string.IsNullOrEmpty(sFilePath))
            {
                frmVerify f = new frmVerify();
                f.DocumentPath = sFilePath;
                f.UserManager = LoadUserDatabase();
                f.ShowDialog(null);
            }
        }

        private IUserManager LoadUserDatabase()
        {
            string sDataPath = Environment.GetFolderPath
                (Environment.SpecialFolder.ApplicationData) + "\\users.xml";
            return new UserManagerXML(sDataPath);
        }
        #endregion

        #region VSTO generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InternalStartup()
        {
            this.Startup += new System.EventHandler(ThisAddIn_Startup);
            this.Shutdown += new System.EventHandler(ThisAddIn_Shutdown);
        }
        
        #endregion
    }
}
